#include "buffer.h"

int buffer_test(void)
{
    printf("** buffer test:\n");
    buffer_t *buf = buffer_new(0);
    assert(buf);
    assert(buffer_len(buf) == 0);

    int i;
    char *data = "GET /index.html HTTP/1.0\r\nConnection: Close\r\n\r\n";
    size_t len = strlen(data);
    for(i = 0; i < 1024; ++i){
        assert(buffer_add(buf, data, len) == 0);
    }
    printf("buffer_add ok\n");
    printf("buffer len: %u\n", buffer_len(buf));
    assert(buffer_len(buf) == (len * 1024));

    for(i = 0; i < 128; ++i){
        uint8_t *p = buffer_getline(buf, NULL);
        printf("line: %s\n", p);
    }

    len = buffer_len(buf);
    char *p = (char *)MALLOC(len);
    assert(p);
    if(buffer_get(buf, p, len) < len){
        printf("buffer_get fail");
        assert(0);
    }
    safe_free(p);

    assert(buffer_len(buf) == 0);
    printf("buffer_get ok\n");

    assert(buffer_snprintf(buf, "hello %s ", "buffer module") == 0);
    assert(buffer_snprintf(buf, "hello %s again", "buffer module") == 0);
    len = buffer_len(buf);
    p = (char *)MALLOC(len + 1);
    assert(p);
    assert(buffer_get(buf, p, len) == len);
    printf("data: %s\n", p);
    safe_free(p);

    buffer_destroy(&buf);

    printf("** buffer test success\n");
    return 0;
}
